#!/usr/bin/env python2.7
#coding=utf-8
import json
import urllib2

class Zabbix():
    header = {"Content-Type": "application/json"}
    zabbix_key = ''
    def __init__(self,url,user,password):
        self.url = url + '/api_jsonrpc.php'
        self.user = user
        self.password = password
        self.get_key()

    def data_format(self,method,params,get_auth=None):
        data = {
            "auth": Zabbix.zabbix_key,
            "id": 1,
            "jsonrpc": "2.0",
            "method": "",
            "params": {},
        }

        if get_auth:
            del data['auth']

        data["method"] = method
        data["params"] = params
        data = json.dumps(data)
        return data

    def http_request(self,data):
        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key,self.header[key])
        result = urllib2.urlopen(request)
        response = json.loads(result.read())
        # print result.read()
        # print response
        result.close()
        if len(response['result']) > 0:
            return response['result']

    def get_key(self):
        get_auth = True
        method = "user.login"
        params = {
                    "user": self.user,
                    "password": self.password
                }

        data = self.data_format(method,params,get_auth)
        Zabbix.zabbix_key = self.http_request(data)
        return  Zabbix.zabbix_key

    def get_template_id(self,template_name):
        method = "template.get"

        params = {
                "output": "extend",
                "filter": {"host": [template_name]}
                  }

        data = self.data_format(method,params)
        result = self.http_request(data)

        try:
            template_id = result[0]['templateid']
        except TypeError as e:
            if 'NoneType' in str(e):
                pass
                #print 'Do not have this template'
        else:
            template_id=result[0]['templateid']
            return template_id

    def get_host_id(self,host_name):
        method = "host.get"
        params = {
                  "output": ["hostid", "name"],
                  "filter": {"host": host_name}
                 }

        data = self.data_format(method,params)
        result = self.http_request(data)
        hostid = result[0]['hostid']
        return hostid

    def create_template(self,template_name):
        method = "template.create"
        params =  {
                "host": template_name,
                "groups": {
                    "groupid": 1
                },
                "templates": [
                    {
                        "templateid": "10001"
                    }
                ]
            }

        data = self.data_format(method, params)
        result = self.http_request(data)
        return result

cmd = Zabbix('{{ zabbix_url }}','{{ zabbix_api_user }}','{{ zabbix_api_pass }}')

result=cmd.get_template_id('{{ appname }}')

if result == None:
    cmd.create_template('{{ appname }}')
    print 'successful'
else:
    print 'Template has been exist'
